<?php
/**
 * Created by PhpStorm.
 * User: mohuani
 * Date: 2019/4/13
 * Time: 16:37
 */

namespace App\Utils;


use http\Header;

class Util
{
    public static $ch = null;
    private static $redis = null;

    /**
     * 对接口返回格式进行统一格式
     * @param $res
     */
    public function JsonReturn($res)
    {
        header("Access-Control-Allow-Origin: *");
        if (is_array($res)) {
            $returnValue = json_encode($res, JSON_UNESCAPED_UNICODE);
        } else {
            $returnValue = $res;
        }
        echo $returnValue;
    }

    /**
     * @param $curl
     * @param $url
     * @param string $method get/post数据(不填则为GET)
     * @return mixed|string
     */
    public function curlRequest($curl, $url,$method=''){

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
        if($method) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($method));
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        return $data;
    }

    /**
     * @return object|\Redis
     */
    public function getRedis()
    {
        $redisConnect = RedisConnect::getRedisInstance();
        return $redisConnect->getRedis();
    }

    /**
     * @param $xml
     * @return mixed
     */
    public function xmlToArray($xml){
        if (file_exists($xml)) {
            libxml_disable_entity_loader(false);
            $xml_string = simplexml_load_file($xml,'SimpleXMLElement', LIBXML_NOCDATA);
        }else{
            libxml_disable_entity_loader(true);
            $xml_string = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
        }
        $result = json_decode(json_encode($xml_string, JSON_UNESCAPED_UNICODE),true);
        return $result;
    }

    /**
     * @param $arr
     * @return string
     */
    public function array2xml($arr){
        $str="<xml>";
        foreach ($arr as $key=>$value){
            $str.= "<$key>$value</$key>";
        }
        $str.="</xml>";
        return $str;
    }

    /**
     * 获取城市列表
     * @return array
     */
    public function getCityLists():array
    {
        if (file_exists(WEATHER_CITY_LISTS_FILE_JSON)) {
            $cityListFile = file_get_contents(WEATHER_CITY_LISTS_FILE_JSON);
            if ($cityListFile == '') {
                $cityListFile = [];
            } else {
                $cityListFile = json_decode($cityListFile, true);
            }
        } else {
            $cityListFile = [];
        }

        return $cityListFile;
    }

}